<!------------- 钉钉扫码登录 ------------->
<template>
    <div class="loginDiv">
        <div class="logo"></div>

            <el-tabs type="border-card">
                <el-tab-pane label="扫码登录">
                    <div  class="logon_wrapper">
                        <div class="logo_top"></div>
                        <div class="logo_title">中科传媒项目人天管理系统</div>
                        <div  id="ding-login" v-if="isShow == 'ding'"></div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="账号登录">
                    <div  class="logon_wrapper">
                        <div class="logo_top" style="margin-top: -75px"></div>
                        <div class="logo_title" style="margin-bottom: 40px">中科传媒项目人天管理系统</div>
                        <el-form
                                ref="loginForm"
                                :model="loginForm"
                                status-icon
                                label-width="80px"
                                :rules="rules"
                                class="demo-ruleForm">
                            <el-form-item
                                    label="账号"
                                    required
                                    prop="accountNumber">
                                <el-input
                                        prefix-icon="el-icon-user"
                                        maxLength='11'
                                        v-model="loginForm.accountNumber"
                                        placeholder="请输入账号"
                                        style="width: 260px"
                                        autocomplete="off">
                                </el-input>
                            </el-form-item>
                            <el-form-item
                                    label="密码"
                                    required
                                    prop="passWord">
                                <el-input
                                        prefix-icon="el-icon-lock"
                                        type="password"
                                        v-model="loginForm.passWord"
                                        maxLength='200'
                                        placeholder="请输入密码"
                                        style="width: 260px"
                                        autocomplete="off">
                                </el-input>
                            </el-form-item>
                            <div style="text-align: center">
                                <el-button
                                        type="primary"
                                        style="width: 180px;font-size: 17px;margin-top: 20px"
                                        @click="loginAccount('loginForm')"
                                        size="medium">登  录
                                </el-button>
                            </div>

                        </el-form>
                    </div>
                </el-tab-pane>
            </el-tabs>


    </div>
</template>



<script>
import { Message } from 'element-ui'
import { dingAppId,dingAppSecret  } from '@/utils/constant'


// 重定向地址，因为vue用的hash，所以网址后面是 #/
let host = window.location.host
let callbackUrl = `http://`+host+`/#/login`
// let callbackUrl = `http://localhost:9528/#/login`

// 钉钉后台获取的appid和appSecret，appSecret没有用到扫码中
// let appid = (host == '121.36.50.70:9528')? 'dingoagymjc1ukld1py3m7' : (host == '119.45.13.228:9528')? 'dingoaadukaolcobrbnhyo' : 'dingoalmomqwefd7wv0vgh'
// let appSecret = (host == '121.36.50.70:9528')? 'XbJKAbuRMNC14YeopUKEb8HwzgUbjljE9d9enlnlKpGZQsmsomrqemCsIINJOgcs' :  (host == '119.45.13.228:9528') ? 'Dkk1k0nFI8LjkC6KK5k2ZizkY82iqpclho0dnisb_kSyIRhTQ98YP5SXn4S8C3HY' : 'GmLHYvCwHp5icEoAGj8ZLieRyeaA2FbC7G6KvX_RS3zxTK6OlFbunuTN45WZN5si'
let appid = dingAppId
let appSecret = dingAppSecret

let redirect = encodeURIComponent(callbackUrl)
// 官网给的跳转连接格式
let http_url = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${redirect}`)
export default {
    data () {
        return {
            isShow: '', // 控制扫码窗口显示
            // code: qs.parse(window.location.hash.substring(3)).code // 获取的临时登陆码
            url: window.location.href, // 获取的临时登陆码
            loginForm:{
                accountNumber: null,
                passWord: null
            },
            rules: {
                accountNumber: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                ],
                passWord: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                ],
            }
        }
    },
    created() {
        this.getCurrentBrowserCore()
        this.dingLogin()
        // 如果临时登录吗存在，执行登录方法
        if(this.url){
            // alert(host)
            /* 这里写登录方法 */
            let code = this.getUrlParamsValue("code")
            if (code) {
                this.http_login(code)
                return false
            }else {
                window.location.href= callbackUrl
            }

        }
        // 获取到扫码结果，并且跳转获取临时登录码
        var handleMessage = function (event) {
            var origin = event.origin;
            if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
                // 拿到 loginTmpCode 后，跳转连接拿到临时登陆码，之后返回到跳转的地址，会携带临时登陆码
                var loginTmpCode = event.data;
                let url = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${http_url}&loginTmpCode=${loginTmpCode}`
                // 这边直接打开拼接好的连接，去获取临时登录码，回来地址在下面
                location.href = url
            }
        };
        if (typeof window.addEventListener != 'undefined') {
            window.addEventListener('message', handleMessage, false);
        } else if (typeof window.attachEvent != 'undefined') {
            window.attachEvent('onmessage', handleMessage);
        }
    },
    methods: {
        // 切换钉钉登录
        dingLogin () {
            this.isShow = 'ding'
            // 这边需要用 $nextTick() 方法来等DOM渲染完成后，才能获取到盒子容器（$nextTick 方法见另一篇文章）
            this.$nextTick(() => {
                // 钉钉登录，参数文档中那些其他项就不展示了，按照文档自己配置就可以
                DDLogin({
                    id: "ding-login",
                    goto: http_url,
                    style: "border:none;background-color:#FFFFFF;",
                })
                // 重置扫码登录框的样式，让登录框居中
                let box = document.getElementById('ding-login')
                box.querySelector('iframe').style.position = 'absolute'
                box.querySelector('iframe').style.margin = 'auto'
            })
        },
        http_login(code){
            this.$store.dispatch('user/getLoginUserInfo', code)
                .then(() => {
                    const routeList = JSON.parse(JSON.stringify(this.$router.options.routes))
                    const userButtonIds = JSON.parse(localStorage.getItem("user")).buttonIds
                    let menus = []
                    routeList.forEach(root=>{
                        if (root.children != null){
                            root.children.forEach(child=>{
                                if (!(child.alwaysShow == false || ( child.buttonId) && userButtonIds.indexOf(child.buttonId) == -1)){
                                    if(userButtonIds.indexOf(child.buttonId) != -1){
                                        console.log(child.path,child.buttonId)
                                        menus.push(child.path)
                                    }

                                }
                            })
                        }
                    })
                    if ( menus.length ==  0){
                        Message.error("你没有可以访问的页面")
                    }else {
                        this.$router.push({ path: menus[0], query: this.otherQuery })
                    }
                    // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
                    // this.loading = false
                    // MessageBox.close()
                })
                .catch((error) => {
                    // Message.error("扫码登录失败")
                    // this.loading = false
                    window.location.href = callbackUrl  //返回 url
                    history.go(0) // 刷新当前页面
                })
        },
        loginAccount(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$store.dispatch('user/getLoginUserInfoByAccount', this.loginForm).then(() => {
                        this.$router.push({ path:  '/logEdit'})
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        getUrlParamsValue(paramName){
            let url = window.location.href
            let paramStr = url.split('?')[1] //参数字符串
            if (paramStr != null){
                let params = paramStr.split('&')
                let code;
                params.forEach(param=>{
                    let p = param.split('=')
                    if (p[0] == paramName){
                        code = p[1]
                    }
                })
                return code
            }else {
                return null
            }
        },
        getCurrentBrowserCore(){
            let code = this.getUrlParamsValue("code")
            if(!code){
                // 获取
                let explorer = window.navigator.userAgent;
                console.log(explorer)
                if(explorer.indexOf("Chrome") == -1){
                    this.promptBox()
                }
            }
        },
        promptBox(){
            this.$confirm('为了保证最佳的体验，建议您使用谷歌浏览器登录本系统！', {
                confirmButtonText: '我知道了',
                center: true,
                showClose: false,
                showCancelButton: false,
                confirmButtonClass: 'confirmButtonText-class',
                closeOnPressEscape:false,
                closeOnClickModal: false,
            }).then(() => {})
            // setTimeout(() => {
            //     MessageBox.close();
            // }, 3000);
        }



    }
}
</script>


<style>
.loginDiv{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: center;
}

</style>
<style lang="less"  >

.loginDiv{
    width: 100%;height: 100%;
    background-image: linear-gradient(180deg, #73CDFF 0%, #3F9EFF 100%);
    div{
       /deep/ .login_content {
            height: 350px !important;
        }

    }
}
.login_qrcode_text{
    margin-bottom: 26px;
}
.logon_wrapper{
    align-self: center;
    // margin-top: -400px;
    width: 365px;
    display: flex;
    flex-direction: column;
    background-color: white;
    justify-content: center;
    align-content: center;
    height: 430px;
    .logo_top{
        background-image: url("../../img/logo.png");
        width: 100px;
        height: 80px;
        background-size: contain;
        background-repeat: no-repeat;
        align-self: center;
    }
    .logo_title{
        font-family: PingFangSC-Semibold;
        font-size: 26px;
        color: #3F9EFF;
        letter-spacing: 0;
        align-self: center;
        font-weight: bold;
    }
    #ding-login{
        width: 365px;
        height: 300px;
    }
}
.logo{
    width: 40%;
    max-width: 40%;
    height: 60%;
    background-image: url("../../img/login_bg2.png");
    background-size: contain;
    background-repeat: no-repeat;
    margin-right: 100px;
    margin-left: -120px;
}
.confirmButtonText-class{
    background-color: #f56c6c !important;
    background: #f56c6c !important;
    border-color: #f56c6c !important;
    color: #ffffff !important;
    width: 110px;
}
.el-tabs__item{
    width: 199px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
}
// .login_content{
//     align-self: center;
//     display: flex;
//     flex-direction: row;
//     flex-wrap: nowrap;
//     justify-content: center;
//     align-items: center;
//     width: 100%;
//     height: 100%;

// }

</style>
